package com.example.demo.socket.duplex;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 双向通讯-客户端
 *
 * @author: htc
 * @date: Created in 11:31 2018/11/29.
 */
public class ClientServer {

    /**
     * @param host
     * @param port
     * @param msg
     */
    public static void client(String host, Integer port, String msg) throws IOException {
        //与服务器建立连接
        Socket socket = new Socket(host, port);

        //获取输出流(向服务器发送数据)
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(msg.getBytes("UTF-8"));
        //发送完毕
        socket.shutdownOutput();

        //获取输入流（获取服务器的反馈信息）
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder s = new StringBuilder();
        while ((len = inputStream.read()) != -1) {
            s.append(new String(bytes, 0, len, "UTF-8"));
        }
        System.out.println("get feedback from server: " + s);
        socket.shutdownInput();

        inputStream.close();
        outputStream.close();
        socket.close();
    }

    public static void main(String[] args) throws IOException {
        client("127.0.0.1", 1111, "Halloween");
    }
}
